package com.itfitness.googlemappoi

import android.location.Address
import android.location.Geocoder
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.TextView
import androidx.activity.viewModels
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.CollectionUtils
import com.blankj.utilcode.util.LogUtils
import com.blankj.utilcode.util.ToastUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.viewholder.BaseViewHolder
import com.google.android.gms.common.ConnectionResult
import com.google.android.gms.common.GooglePlayServicesUtil
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationServices
import com.google.android.gms.maps.CameraUpdateFactory
import com.google.android.gms.maps.GoogleMap
import com.google.android.gms.maps.GoogleMap.OnCameraChangeListener
import com.google.android.gms.maps.MapsInitializer
import com.google.android.gms.maps.OnMapReadyCallback
import com.google.android.gms.maps.model.CameraPosition
import com.google.android.gms.maps.model.LatLng
import com.google.android.gms.tasks.OnSuccessListener
import com.itfitness.googlemappoi.base.BaseActivity
import com.itfitness.googlemappoi.bean.GeocodeAddressBean
import com.itfitness.googlemappoi.databinding.ActivityMainBinding
import com.itfitness.googlemappoi.http.RetrofitManger
import com.itfitness.googlemappoi.utils.LocationUtils
import com.itfitness.googlemappoi.viewmodel.MainModel
import okhttp3.ResponseBody
import retrofit2.Call
import java.lang.Exception
import java.util.*
import kotlin.math.ln

class MainActivity : BaseActivity(), OnMapReadyCallback{
    private val mainModel: MainModel by viewModels()
    private lateinit var googleMap: GoogleMap
    private var baseQuickAdapter: BaseQuickAdapter<GeocodeAddressBean.ResultsDTO,BaseViewHolder>? = null
    private lateinit var mainBinding: ActivityMainBinding
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        mainBinding = DataBindingUtil.setContentView(this,R.layout.activity_main)
        mainBinding.lifecycleOwner = this
        initMap(savedInstanceState)
        initObserve()
    }

    /**
     * 加载数据的监听
     */
    private fun initObserve() {
        addObserve(mainModel.userInfo,{
            if(!CollectionUtils.isEmpty(it.results)){
                initAddressAdapter(it.results)
            }
        },{
            LogUtils.eTag("错误",it.message)
        })
    }

    /**
     * 加载地址适配器
     */
    private fun initAddressAdapter(results: List<GeocodeAddressBean.ResultsDTO>) {
        if(baseQuickAdapter == null){
            baseQuickAdapter = object : BaseQuickAdapter<GeocodeAddressBean.ResultsDTO,BaseViewHolder>(R.layout.item_address,results.toMutableList()){
                override fun convert(holder: BaseViewHolder, item: GeocodeAddressBean.ResultsDTO) {
                    holder.setText(R.id.rv_address,item.formatted_address)
                }
            }
            mainBinding.rvAddress.apply {
                layoutManager = LinearLayoutManager(this@MainActivity)
                adapter = baseQuickAdapter
            }
        }else{
            baseQuickAdapter!!.setNewInstance(results.toMutableList())
        }
    }

    private fun initMap(savedInstanceState: Bundle?) {
        mainBinding.map.onCreate(savedInstanceState)
        try {
            MapsInitializer.initialize(this)
        } catch (e: Exception) {
            e.printStackTrace()
        }
        val errorCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this)
        if (ConnectionResult.SUCCESS != errorCode) {
            GooglePlayServicesUtil.getErrorDialog(errorCode, this, 0).show()
        } else {
            mainBinding.map.getMapAsync(this)
        }
    }

    override fun onResume() {
        super.onResume()
        mainBinding.map.onResume()
    }

    override fun onMapReady(map: GoogleMap?) {
        map?.let {
            googleMap = it
        }
        //默认设置一个位置，要不获取不到位置的话就到海里了
        val currencyLatLng = LatLng(36.659584, 117.144005)
        googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currencyLatLng, 16f))
        getCurrentLocation()
        //获取地图中心位置
        googleMap.setOnCameraMoveListener {
            with(googleMap.cameraPosition.target){
                Log.e("地图中心位置","Lat：$latitude，Lng：$longitude")
                mainModel.getAddress(latitude,longitude)
            }
        }
    }

    /**
     * 获取当前位置
     */
    private fun getCurrentLocation() {
        LocationUtils.getInstance(this).addressCallback = object : LocationUtils.AddressCallback{
            override fun onGetAddress(address: Address?) {
            }
            override fun onGetAddressFailde() {

            }
            override fun onGetLocation(lat: Double, lng: Double) {
                val currencyLatLng = LatLng(lat, lng)
                googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(currencyLatLng, 16f))
            }
        }
    }

}